package com.linkin.homepage.ui.home;

import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.linkin.homepage.R;
import com.linkin.homepage.app.PreloadApi;
import com.linkin.homepage.base.BaseFragment;
import com.linkin.homepage.base.rxbase.RxManager;
import com.linkin.homepage.base.util.Predictor;
import com.linkin.homepage.base.viewmapping.ViewMapping;
import com.linkin.homepage.bean.ExamDataBean;
import com.linkin.homepage.bean.HomeDataResponse;
import com.linkin.homepage.ui.home.exam.ExamFragment;
import com.linkin.homepage.view.PagerSlidingTabStrip;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页Fragment
 */
@ViewMapping(R.layout.fragment_main)
public class MainFragment extends BaseFragment implements OnReClickListener {

    private static final String JUMP_ID = "jump_id";
    private static final String TAG = "MainFragment";

    PagerSlidingTabStrip mPagerSlidingTabStrip;
    ViewPager2 mViewPager;

    private RxManager mRxManager = null;
    private PagerAdapter mPagerAdapter = null;

    private final ArrayList<String> mTitleList = new ArrayList<>();
    private final List<String> mExamIdIdList = new ArrayList<>();
    private final SparseArray<Fragment> mFragmentList = new SparseArray<>();

    public static MainFragment newInstance(String jumpId) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(JUMP_ID, jumpId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View rootView) {
        initRxManager();
        initViewPager();
    }

    @Override
    protected void clear() {
        mRxManager.clear();
    }

    private void initRxManager() {
        mRxManager = new RxManager();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isAlive()) {
            if (isVisibleToUser && isShowingFailed()) {
                refreshData();
            }
            Fragment fragment = mFragmentList.get(mViewPager.getCurrentItem());
            if (fragment != null) {
                fragment.setUserVisibleHint(isVisibleToUser);
            }
        }
    }

    /**
     * 事件处理
     */
    @Override
    public void onReClick() {
        if (isAlive()) {
            int index = mViewPager.getCurrentItem();
            Fragment fragment = mFragmentList.get(index);
            if (fragment instanceof OnReClickListener) {
                ((OnReClickListener) fragment).onReClick();
            }
        }
    }

    /**
     * request data
     */
    @Override
    protected void initData() {
        refreshData();
    }

    @Override
    protected void refreshData() {
        showLoading();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showNormal();
                showChannels(PreloadApi.getHomeData());
            }
        }, 2 * 1000);
    }

    /**
     * view显示
     */
    private void showChannels(HomeDataResponse.HomeDataInfo r) {
        if (r == null) {
            return;
        }

        for (ExamDataBean examData : r.exam_data) {
            mTitleList.add(examData.getName());
            mExamIdIdList.add(examData.getExamId());
        }

        mPagerSlidingTabStrip.setTitleList(mTitleList);
        mPagerAdapter.notifyDataSetChanged();

        int position = 1;
        if (getArguments() != null) {
            String jumpId = getArguments().getString(JUMP_ID);
            if (Predictor.isNotEmpty(jumpId)) {
                try {
                    for (int i = 0; i < mExamIdIdList.size(); i++) {
                        if (mExamIdIdList.get(i).equals(jumpId)) {
                            position = i;
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        mViewPager.setCurrentItem(position, false);
    }

    /**
     * ViewPager
     */
    private void initViewPager() {
        mViewPager = getRootView().findViewById(R.id.first_view_pager);
        mPagerSlidingTabStrip = getRootView().findViewById(R.id.pager_sliding_tab_strip);

        mPagerAdapter = new PagerAdapter(this);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(1);

        mPagerSlidingTabStrip.setViewPager(mViewPager);
        mPagerSlidingTabStrip.setLeftInterpolator(new AccelerateInterpolator(1.2f));
        mPagerSlidingTabStrip.setRightInterpolator(new DecelerateInterpolator(1.2f));

        mPagerSlidingTabStrip.setOnPageChangeListener(new PagerSlidingTabStrip.OnPageSelectedListener() {
            @Override
            public void onPageSelected(int position) {
                if (position >= 0 && position < mTitleList.size()) {
//                    BuriedPointUtils.getInstance().setBuried(BuriedPointTag.ChangeHomeChannel, mTitleList.get(position),
//                            null, null, null, null, null, null);
                }
            }
        });
    }

    private class PagerAdapter extends FragmentStateAdapter {

        public PagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        public PagerAdapter(@NonNull Fragment fragment) {
            super(fragment);
        }

        public PagerAdapter(@NonNull FragmentManager fragmentManager, @NotNull Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NotNull
        @Override
        public Fragment createFragment(int position) {
            String channelTitle = mTitleList.get(position);
            String channelId = mExamIdIdList.get(position);
            Fragment fragment = ExamFragment.newInstance(channelId, channelTitle);
            if (!getUserVisibleHint()) {
                fragment.setUserVisibleHint(false);
            }
            mFragmentList.put(position, fragment);
            return fragment;
        }

        @Override
        public int getItemCount() {
            return mExamIdIdList.size();
        }
    }
}
